//
//  YFNetworkManager.swift
//  YFSwiftWeibo
//
//  Created by tsaievan on 2017/8/28.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit
import AFNetworking

enum YFHTTPMethod {
    case GET
    case POST
}

class YFNetworkManager: AFHTTPSessionManager {
    
//    var accessToken: String? //= "2.00Fn5ISBvPu6aE799b20259a1wG5TB"
    lazy var tokenModel = YFAccessTokenModel()
    
    
    /// 计算型属性, 当accessToken为空, 则userLogon为false, 当accessToken不为空, 则userLogon为true
    var userLogon: Bool {
        return tokenModel.access_token != nil
    }
    
    // swift中的单例
    static let shared: YFNetworkManager = {
       let instance = YFNetworkManager()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    func tokenRequest(method: YFHTTPMethod = .GET, URLString: String, parameters: Any?, completion: @escaping (_ json: [String : Any]?, _ isSuccess : Bool)->()) {
        
        ///< 0. 判断token 是否为nil, 为nil直接返回
        guard let token = tokenModel.access_token else {
            ///< 0. 判断token是否为nil, 为nil直接返回, 程序执行过程中, 一般token不会为nil
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: YFWeiboUserLoginNotification), object: nil)
            completion(nil, false)
            return
        }
        
        ///< 1. 判断参数字典是否存在, 如果为nil, 应该新建一个字典
        var parameters = parameters as? [String : Any]
        if parameters == nil {
            ///< 实例化字典
            parameters = [String : Any]()
        }
        
        ///< 2. 设置参数字典, 代码在此处字典一定有值, 可以强行解包
        parameters!["access_token"] = token
        
        ///< 3. 调用request发起真正的网络请求
        request(URLString: URLString, parameters: parameters) { (json, isSuccess) in
            completion(json, isSuccess)
        }
    }
    
    func request(method: YFHTTPMethod = .GET, URLString: String, parameters: Any?, completion: @escaping (_ json: [String : Any]?, _ isSuccess : Bool)->()) {
        
        let success = {
            (task: URLSessionDataTask, json: Any?)->() in
            completion(json as? [String : Any], true)
        }
        
        let failure = {
            (task: URLSessionDataTask?, error: Error)->() in
            
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                //FIXME: -发送通知, token过期, 提示用户再次登录
                print("token过期")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: YFWeiboUserLoginNotification), object: "bad token")
            }
            
            print("网络加载失败:\(error)")
            completion(nil, false)
        }
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}


